let Collider = require("Collider");

cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //    default: null,      // The default value will be used only when the component attaching
        //                           to a node for the first time
        //    url: cc.Texture2D,  // optional, default is typeof default
        //    serializable: true, // optional, default is true
        //    visible: true,      // optional, default is true
        //    displayName: 'Foo', // optional
        //    readonly: false,    // optional, default is false
        // },
        // ...
        
        // 暂存 bulletManager 对象的引用
        bulletManager: {
            default: null,
            serializable: false
        },

        // collider type : 使用于碰撞检测时，根据碰撞类型执行不同的动作
        COLLIDER_TYPE: {
            visible: false,
            default: Collider.type.PLAYER_BULLET,
            type: cc.Integer,
        },
        
        // alive timer
        timer : 0,
        // alive max time in second
        aliveMaxTime : 1,
        // ability
        attack : 2,
    },

    // use this for initialization
    onLoad: function () {
    },
    
    init: function (bulletManager) {
        if (bulletManager) {
            this.bulletManager = bulletManager;
        }
        this.alive = true;
        this.timer = 0;
    },

    unuse: function () {
        this.bulletManager = null;
    },

    reuse: function (bulletManager) {
        this.bulletManager = bulletManager; // get 中传入的管理类实例
    },
    
    hit : function () {
        this.bulletManager.put(this.node);
        this.alive = false;
    },
    
    onCollisionEnter: function (other, self) {
        if (this.alive) {
            let ocpt = other.node.getComponent(other.node.name);
            if (ocpt.COLLIDER_TYPE === Collider.type.ENEMY) {
                this.hit();
            }
        }
    },

    // called every frame, uncomment this function to activate update callback
    update: function (dt) {
        if (!this.alive) return ;
        // update timer
        this.timer += dt;
        
        // 如果在生存周期之内
        if (this.timer < this.aliveMaxTime) {
            this.node.y += 1000 * dt;
        } else {
            this.alive = false;
            this.bulletManager.put(this.node);
        }
    },
});
